<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>个人信息管理</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="4">
          <el-button type="primary" @click="editDialogVisible = true">修改信息</el-button>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="editPasswordVisible = true">修改密码</el-button>
        </el-col>
        <!-- <el-col :span="4">
          <el-button type="primary" @click="addressManageVisible = true">收货地址管理</el-button>
        </el-col> -->
      </el-row>

      <!-- 用户信息区域 -->
      <el-table :data="userlist" border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="用户名" prop="username"></el-table-column>
        <el-table-column label="真实姓名" prop="realName"></el-table-column>
        <el-table-column label="电话号码" prop="phoneNumber"></el-table-column>
        <el-table-column label="年龄" prop="age"></el-table-column>
        <el-table-column label="性别" prop="sex"></el-table-column>
      </el-table>
    </el-card>

    <!-- 修改用户的对话框 -->
    <el-dialog title="修改信息" :visible.sync="editDialogVisible" width="50%" @close="editDialogClosed">
      <el-form :model="userlist[0]" :rules="editFormRules" ref="editFormRef" label-width="100px">
        <el-form-item label="用户名">
          <!-- disabled 用户名不可改 -->
          <el-input v-model="userlist[0].username" disabled></el-input>
        </el-form-item>
        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="userlist[0].realName"></el-input>
        </el-form-item>
        <el-form-item label="电话号码" prop="phoneNumber">
          <el-input v-model="userlist[0].phoneNumber"></el-input>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input v-model="userlist[0].age"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select v-model="userlist[0].sex" style="width: 100%">
            <el-option v-for="item in options" :key="item.id" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改密码的对话框 -->
    <el-dialog title="修改密码" :visible.sync="editPasswordVisible" width="50%" @close="editDialogClosed">
      <el-form :model="userPassword" :rules="editFormRules" ref="editPasswordRef" label-width="100px">
        <el-form-item label="原始密码">
          <el-input v-model="userPassword.oldPassword" placeholder="输入密码"></el-input>
        </el-form-item>
        <el-form-item label="新密码">
          <el-input v-model="userPassword.newPassword" placeholder="输入密码"></el-input>
        </el-form-item>
        <el-form-item label="确认密码">
          <el-input v-model="userPassword.repeatnewPassword" placeholder="输入密码" @blur="surePassword"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editPassword">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    // 验证邮箱的规则
    var checkEmail = (rule, value, cb) => {
      // 验证邮箱的正则表达式
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/

      if (regEmail.test(value)) {
        // 合法的邮箱
        return cb()
      }

      cb(new Error('请输入合法的邮箱'))
    }

    // 验证手机号的规则
    var checkMobile = (rule, value, cb) => {
      // 验证手机号的正则表达式
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/

      if (regMobile.test(value)) {
        return cb()
      }

      cb(new Error('请输入合法的手机号'))
    }

    return {
      // 获取用户列表的参数对象
      queryInfo: {
        query: '',
        // 当前的页数
        pagenum: 1,
        // 当前每页显示多少条数据
        pagesize: 2,
      },
      userlist: [],
      // userinfo: {},
      options: [
        {
          value: 0,
          label: '男',
        },
        {
          value: 1,
          label: '女',
        },
      ],
      total: 0,
      // 控制添加用户对话框的显示与隐藏
      editDialogVisible: false,
      editPasswordVisible: false,
      addressManageVisible: false,
      // 添加用户的表单数据
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: '',
      },
      // 添加表单的验证规则对象
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '用户名的长度在3~10个字符之间',
            trigger: 'blur',
          },
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 6,
            max: 15,
            message: '用户名的长度在6~15个字符之间',
            trigger: 'blur',
          },
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' },
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' },
        ],
      },
      // 控制修改用户对话框的显示与隐藏
      editDialogVisible: false,
      // 查询到的用户信息对象
      editForm: {},
      // 修改表单的验证规则对象
      editFormRules: {
        email: [
          { required: true, message: '请输入用户邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' },
        ],
        mobile: [
          { required: true, message: '请输入用户手机', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' },
        ],
      },
      // 控制分配角色对话框的显示与隐藏
      setRoleDialogVisible: false,
      // 需要被分配角色的用户信息
      userInfo: {},
      // 所有角色的数据列表
      rolesList: [],
      // 新旧密码
      userPassword: {
        oldPassword: '',
        newPassword: '',
        repeatRealName: '',
      },
      // 已选中的角色Id值
      selectedRoleId: '',
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    // 更新用户列表
    async getUserList() {
      const { data: res } = await this.$http.get('user')
      if (res.status !== 200) {
        return this.$message.error('获取用户列表失败！')
      }
      this.userlist.push(res.data)
      console.log('this.userlist', this.userlist)
      for (var index = 0; index < this.userlist.length; index++) {
        console.log('this.userlist[index].sex', this.userlist[index].sex)
        if (this.userlist[index].sex === 0) {
          this.$set(this.userlist[index], `sex`, '男')
        } else {
          this.$set(this.userlist[index], `sex`, '女')
        }
      }
    },
    // 监听修改用户对话框的关闭事件
    editDialogClosed() {
      this.$refs.editFormRef.resetFields()
    },
    // 修改用户信息并提交
    editUserInfo() {
      // validate和valid进行表单验证
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return
        // 发起修改用户信息的数据请求
        if( this.userlist[0].sex === '男') {
          this.userlist[0].sex = 0
        }else if(this.userlist[0].sex === '女') {
          this.userlist[0].sex = 1
        }
        const { data: res } = await this.$http.put('user', this.userlist[0])

        if (res.status !== 200) {
          return this.$message.error('更新用户信息失败！')
        }

        // 关闭对话框
        this.editDialogVisible = false
        // 刷新数据列表
        this.getUserList()
        location.reload()
        // 提示修改成功
        this.$message.success('更新用户信息成功！')
      })
    },
    editPassword() {
      this.$refs.editPasswordRef.validate(async (valid) => {
        if (!valid) return
        let oldPassword = this.userPassword.oldPassword
        let newPassword = this.userPassword.newPassword
        const { data: res } = await this.$http.put('user/password', { oldPassword, newPassword })
        if (res.status !== 200) {
          return this.$message.error(res.message)
        }

        // 关闭对话框
        this.editPasswordVisible = false
        // 刷新数据列表
        this.getUserList()
        location.reload()

        // 提示修改成功
        this.$message.success('修改密码成功！')
      })
    },
    // 确认密码
    surePassword() {
      if (this.userPassword.newPassword != this.userPassword.repeatnewPassword) {
        this.$message.error('两次输入密码不一致')
      }
    },
  },
}
</script>

<style lang="less" scoped>
</style>
